package com.zxl.live.screen.screen.ui.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import java.util.ArrayList;
import java.util.List;

/**
 * 屏幕广播
 */
public class ScreenReceiver extends BroadcastReceiver {

	private boolean mIsRegister;

	private static List<ScreenStatusListener> mCache = new ArrayList<>();

	public void registerReceiver(Context context) {
		if (!mIsRegister) {
			mIsRegister = true;
			IntentFilter filter = new IntentFilter();
			filter.addAction(Intent.ACTION_SCREEN_OFF);
			filter.addAction(Intent.ACTION_SCREEN_ON);
			context.registerReceiver(this, filter);
		}
	}
	
	public void unregisterReceiver(Context context) {
		if (mIsRegister) {
			mIsRegister = false;
			context.unregisterReceiver(this);
		}
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (action != null) {
			if (action.equals(Intent.ACTION_SCREEN_ON)) {
				for (ScreenStatusListener screenStatusListener : mCache) {
					screenStatusListener.onScreenOn();
				}
			} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
				for (ScreenStatusListener screenStatusListener : mCache) {
					screenStatusListener.onScreenOff();
				}
			}
		}
	}

	public static void registerListener(ScreenStatusListener listener) {
		if (!mCache.contains(listener)) {
			mCache.add(listener);
		}
	}

	public static void unregisterListener(ScreenStatusListener listener) {
		mCache.remove(listener);
	}

	public interface ScreenStatusListener {

		void onScreenOn();

		void onScreenOff();

	}

}
